package bhwz.seac3.bl.import_.crawler.nbaLive;

import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;

import bhwz.seac3.bl.import_.crawler.Downloader;

public class NBALive {
	private static String detail = "";
	private final static String matchId = "150123";
	private final static String homeTeamName = "勇士";
	private final static String awayTeamName = "骑士";
	private static int count = 0;
	private static String url = "";
	static Downloader down = new Downloader();

	public NBALive() {
		urlSet();
	}

	public void broadCast(Consumer<String> consumer) {
		while (true) {
			detail = getLatest();
			if (!detail.equals("")) {
				consumer.accept(check(detail));
			}
			if (detail.equals("比赛结束"))
				break;
		}
	}

	private String check(String s) {
		Matcher m = Pattern.compile(".*-.*-.*").matcher(s);
		if (m.matches()) {
			nextDetail();
			String next = getLatest();
			if (s.length() > next.length()) {
				return s.substring(getLatest().length());
			} else {
				System.out.println(s.length()+" "+getLatest().length());
				lastDetail();
				while(s.length()<next.length()){
					s = getLatest();
				}
				return s.substring(next.length());

			}
		}
		nextDetail();
		return s;
	}

	private String getLatest() {
		return Jsoup.parse(down.download(url)).text().toString();
	}

	private void nextDetail() {
		count++;
		urlSet();
	}

	private void lastDetail() {
		count--;
		urlSet();
	}

	private void urlSet() {
		url = "http://g.hupu.com/node/playbyplay/matchLives?sid=0&s_count="
				+ count + "&match_id=" + matchId + "&homeTeamName="
				+ homeTeamName + "&awayTeamName=" + awayTeamName;
	}

	public static void main(String[] args) {
		NBALive l = new NBALive();
		l.broadCast(s -> System.out.println(s));
	}
}
